The number 89 is the first integer with more than one digit that fulfills the property >partially introduced in the title of this kata. What's the use of saying "Eureka"? >Because this sum gives the same number.
In effect: 89 = 8^1 + 9^2
The next number in having this property is 135.
See this property again: 135 = 1^1 + 3^2 + 5^3We need a function to collect these numbers, that may receive two integers a, b that >defines the range [a, b] (inclusive) and outputs a list of the sorted numbers in the >range that fulfills the property described above.
Let's see some cases (input -> output):
1, 10 -> [1, 2, 3, 4, 5, 6, 7, 8, 9]
1, 100 -> [1, 2, 3, 4, 5, 6, 7, 8, 9, 89]If there are no numbers of this kind in the range [a, b] the function should output an >empty list.
90, 100 --> []
題目理解:將數字number從第一個數字開始,依序以1,2,3...來做次方,並將所有值相加後若等於number本身,則將此數收集於list中。設計函數以返還列表包含a~b內所有符合此特性的自然數,若無則返還[]。
def sum_dig_pow(a, b):
result = []
for number in range(a,b+1):
#先將待檢驗數字number轉換成列表保存
number_lst = [int(s) for s in str(number)]
sum_num = 0
#利用len()的長度與number位數相符合,配合迴圈使次方遞增
for i in range(len(number_lst)):
sum_num += number_lst[i]**(i+1)
if sum_num == number:
result.append(number)
return result